package spring.beanLoad;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.testng.Assert;
import org.testng.annotations.Test;
import spring.factory.DefaultBeanFactory;
import spring.inters.HelloApi;
import spring.impl.HelloImpl2;
import spring.model.BeanDefinition;

public class BeanFactoryTest {
    @Test
    public void testPrototype() throws Exception {

        DefaultBeanFactory bf = new DefaultBeanFactory();

        BeanDefinition bd = new BeanDefinition();
        bd.setId("bean");
        bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        bd.setClazz(HelloImpl2.class.getName());
        bf.registerBeanDefinition(bd);
        System.out.println(bf.getBean("bean") != bf.getBean("bean"));
    }

    /**
     *
     */
    @Test
    public void testSingleThread() {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("src/main/resources/threadScope.xml");
        HelloApi api1 = beanFactory.getBean("helloApi", HelloApi.class);
        HelloApi api2 = beanFactory.getBean("helloApi", HelloApi.class);
        System.out.println(api1 == api2);

    }

    @Test
    public void testTwoThread() throws InterruptedException {
        final BeanFactory beanFactory = new ClassPathXmlApplicationContext("src/main/resources/threadScope.xml");
        final HelloApi[] beans = new HelloApi[2];
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                beans[0] = beanFactory.getBean("helloApi", HelloApi.class);
            }
        };


        Thread thread2 = new Thread() {
            @Override
            public void run() {
                beans[1] = beanFactory.getBean("helloApi", HelloApi.class);
            }
        };
        thread1.start();
        thread1.sleep(1000);
        thread2.start();
        thread2.sleep(1000);
        Assert.assertEquals(beans[0], beans[1]);
    }


}
